<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 用户自定义函数库
// +----------------------------------------------------------------------
use EasyWeChat\Factory;
use think\Db;
use think\Image;

function conf($val = "", $vals = "")
{
    return config()[$val][$vals];
}

function responseJson($code = 0, $msg = '', $data = null)
{
    $response = array(
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    );
    exit(json_encode($response));
}

function lmcurl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if ($SSL) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function msg($code = 0, $msg = "", $data, $count = 1)
{

    $res['code'] = $code;

    $res['msg'] = $msg;

    $res['data'] = $data;

    $res['count'] = $count;

    exit(arj($res));

}

function arj($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    // if($isformdata) $data = new_stripslashes($data);

    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 获取微信小程序token
 * @return bool|string
 */
function getAccessToken()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function getAccessToken2()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $result = json_decode(file_get_contents($url), true);
    return $result['access_token'];
}

function uploadShippingInfo($access_token, $order_info)
{
    $member_info = Db::name('member')->find($order_info['member_id']);
    $express_info = Db::name('express')->where('name', '=', $order_info['express_name'])->find();
    $shipping_data = [
        'order_key' => [
            'order_number_type' => 1, // 1-微信订单号，2-商户订单号
            'out_trade_no' => $order_info['order_no'],
            'mchid' => '1713433592'
        ],
        'logistics_type' => 1, // 1-物流配送，2-同城配送，3-自提
        'delivery_mode' => 1,
        'shipping_list' => [
            [
                'tracking_no' => $order_info['express_no'],
                'express_company' => $express_info['code2'],
//                'express_company' => '',
//                'shipping_company_name' => '物流公司名称（如顺丰）',
                'item_desc' => '商品购买'
            ]
        ],
        'upload_time' => "2024-10-18T16:50:27+08:00", // 时间戳
        'payer' => [
            'openid' => $member_info['openid']
        ]
    ];

    // 微信API地址
    $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token={$access_token}";

    // 转换为JSON
    $json_data = json_encode($shipping_data, JSON_UNESCAPED_UNICODE);

//    dump($json_data);
//    die;

    // 初始化CURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json_data)
    ]);

    // 执行请求
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // 解析响应
    $result = json_decode($response, true);

    if ($http_code !== 200 || !$result) {
        return [
            'success' => false,
            'error' => '请求失败或返回数据异常',
            'http_code' => $http_code,
            'response' => $response
        ];
    }

    if (isset($result['errcode']) && $result['errcode'] != 0) {
        return [
            'success' => false,
            'error' => $result['errmsg'] ?? '微信接口返回错误',
            'errcode' => $result['errcode'],
            'response' => $result
        ];
    }

    return [
        'success' => true,
        'data' => $result
    ];
}

//发货(不用)
function sendDelivery($access_token, $order_id, $delivery_company, $delivery_id)
{
    $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token={$access_token}";

    $data = [
        'order_key' => [
            'order_number_type' => 1, // 1-微信订单号
            'order_number' => $order_id
        ],
        'logistics_type' => 1, // 1-物流配送
        'shipping_list' => [
            [
                'delivery_id' => $delivery_id,
                'delivery_name' => $delivery_company
            ]
        ],
        'shipping_type' => 1, // 1-正常快递
        'upload_time' => time()
    ];

    $options = [
        'http' => [
            'method' => 'POST',
            'header' => 'Content-type: application/json',
            'content' => json_encode($data)
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return json_decode($result, true);
}

//查询物流
function queryDelivery($access_token, $order_id)
{
    $url = "https://api.weixin.qq.com/wxa/sec/order/getshippinginfo?access_token={$access_token}";

    $data = [
        'order_key' => [
            'order_number_type' => 1, // 1-微信订单号
            'order_number' => $order_id
        ]
    ];

    $options = [
        'http' => [
            'method' => 'POST',
            'header' => 'Content-type: application/json',
            'content' => json_encode($data)
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return json_decode($result, true);
}


function getDistance($from, $to)
{
//
    $lastPos = strrpos($to, ';');
    if ($lastPos !== false) {
        $to = explode(';', $to)[1];
    }
//
    $to = explode(',', $to);

    $from = explode(',', $from);

    $radLat1 = deg2rad(floatval($to[1]));// deg2rad()函数将角度转换为弧度

    $radLat2 = deg2rad(floatval($from[1]));

    $radLng1 = deg2rad(floatval($to[0]));

    $radLng2 = deg2rad(floatval($from[0]));

    $a = $radLat1 - $radLat2;

    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return round($s, 2);
}

//通过IP获取地址
function getDistrictByIP($ip)
{
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($data && $data['status'] === 'success') {
        return $data['city']; // 返回区县名
    } else {
        return 'Unknown';
    }
}

//获取订单号
function GetOrderSN($type, $data = array())
{

    if ($type == 1) {


        $city_code = cityCode($data);

        $time = date('ymd');

        $lennum = lennum();

        $ordersn = $time . $city_code . $lennum;

        return $ordersn;
    }

    if ($type == 2) {
        $order_id_main = date('YmdHis') . rand(100000, 999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }
}

/**
 * 区号
 */

function cityCode($data)
{
    $los = $data['lat'] . ',' . $data['lng'];

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $los . "&key=" . config('MapKey') . "&type=json";

    $res = lmcurl($url);

    $city = string2array($res);


    if ($city['status'] != 0) {

        GetOrderSN(1, $data);

    }
    $ad_info = $city['result']['ad_info'];

    $length = strlen($ad_info['phone_area_code']);

    $city_code = $ad_info['phone_area_code'];

    if ($length > 3) {
        $city_code = substr($city_code, 1, 3);
    }

    return $city_code;
}

/**
 * 根据地址返回坐标
 */
function getLWByAddress($address)
{
    $key = config('wechat.geocodeMap_1');
    $url = 'https://restapi.amap.com/v3/geocode/geo?key=' . $key . '&address=' . urlencode($address);
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == '1') {
        $jsonResponse['geocodes'][0]['location'] = explode(',', $jsonResponse['geocodes'][0]['location']);
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['geocodes'][0]['location']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 * 获取前天时间戳范围默认昨天
 */
function getTimestamp($day = -1)
{
    $data_string = $day . " day";
    $yesterday = date("Y-m-d", strtotime($data_string));

// 昨天开始时间戳
    $yesterdayStartTimestamp = strtotime($yesterday . " 00:00:00");

// 昨天结束时间戳
    $yesterdayEndTimestamp = strtotime($yesterday . " 23:59:59");

    return array(
        0 => $yesterdayStartTimestamp,
        1 => $yesterdayEndTimestamp
    );
}

function objectToArray($object)
{
    $jsonString = json_encode($object);
    $array = json_decode($jsonString, true);

    return $array;
}

//生成小程序二维码
function qrcode($value, $page, $width = 600)
{
    try {
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit($value, [
            'page' => $page,
            'width' => $width,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time());
            return config('wechat.url') . '/uploads/drivingcode/' . $filename;
        }
//        msg(-1, '', $response);
        return $response;
    } catch (\Exception $e) {
//        msg(-1, $e->getMessage(), '');
        return $e->getMessage();
    }
}

function showMsg($status, $message = '', $data = array())
{
    $result = array(
        'status' => $status,
        'message' => $message,
        'data' => $data
    );
    exit(json_encode($result));
}

function formatSizeUnits($bytes)
{
    if ($bytes >= 1073741824) {
        // 大于等于 1 GB
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        // 大于等于 1 MB
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        // 大于等于 1 KB
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } else {
        // 小于 1 KB
        $bytes = $bytes . ' Bytes';
    }
    return $bytes;
}

//1看视频 2兑换 3其他
function addFraction($memberId, $fraction_count = 2, $desc = ' ', $type = 1, $is_count = 1)
{
    $insert_data = array(
        'member_id' => $memberId,
        'create_time' => time(),
        'count' => $fraction_count,
        'desc' => $desc,
        'type' => $type,
        'is_count' => $is_count,
    );
    Db::name('fraction_record')->insertGetId($insert_data);
    if ($is_count == 1) {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setInc('fraction', $fraction_count);
    } else {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setDec('fraction', $fraction_count);
    }
}

//获取优惠券
function getCoupons($memberId, $coupon_info, $get_type = 1, $invite_member_id = 0)
{
    $now_time = time();
    $insert_data = array(
        'member_id' => $memberId,
        'coupon_id' => $coupon_info['id'],
        'name' => $coupon_info['name'],
        'value' => $coupon_info['value'],
        'min_amount' => $coupon_info['min_amount'],
        'claimed_time' => $now_time,
        'start_time' => $now_time,
        'create_time' => time(),
        'get_type' => $get_type,
        'invite_member_id' => $invite_member_id,
        'desc' => $coupon_info['desc']
    );
    if ($coupon_info['effect_type'] == 1) {
        $insert_data['end_time'] = $coupon_info['effect_end'];
    } else {
        $insert_data['end_time'] = $now_time + ($coupon_info['effect_day'] * 86400);
    }
    //领取张数
    Db::name('coupons')
        ->where('id', '=', $coupon_info['id'])
        ->setInc('claimed_count');
    //增加会员优惠券
    $result_id = Db::name('member_coupons')->insertGetId($insert_data);
    return $result_id;
}

//订单回调
function orderPaySuccess($order_data, $pay_type = 1)
{
    $order_update = array(
        'id' => $order_data['id'],
        'status' => 2,
        'pay_time' => time(),
        'pay_status' => 1,
        'pay_type' => $pay_type
    );
    Db::startTrans();
    try {
        if ($pay_type == 2) {
            $order_update['pay_money'] = $order_data['order_money'];
        }
        $member_info = Db::name('member')->find($order_data['member_id']);
        if ($member_info['is_clock'] != 1) {
            Db::name('member')->update([
                'id' => $order_data['member_id'],
                'is_clock' => 1
            ]);
        }
        Db::name('order')->update($order_update);
        if ($order_data['mc_id']) {
            $mc_update = array(
                'id' => $order_data['mc_id'],
                'status' => 3,
            );
            Db::name('member_coupons')->update($mc_update);
        }
        //升级会员
        upVip($order_data);
        //升级首席代理
        upDl($order_data);

        //980 推荐人 买了9980 的商品 更改上级关系
        editUp($order_data);
        //普通返现
        returnMoney($order_data);
        //级差返佣
        jiChaMoney($order_data);
        //9980平级将
        PJMoney1($order_data);
        //董事股东分红管理&&董事平级奖励
        DSGDfxMoney($order_data);

        Db::commit();
        return 1;
    } catch (\Exception $e) {
        Db::rollback();
        return $e;
    }
}

// 980 推荐人 买了9980 的商品 更改上级关系
function editUp($order_data)
{
    $member_info = Db::name('member')->find($order_data['member_id']);
    //是否购买代理产品
    $is_dl_goods = 0;
    $order_goods_ids = Db::name('order_goods')->where([
        'order_id' => $order_data['id']
    ])->column('goods_id');
    $goods_up_list = Db::name('goods_up')->where('goods_id', 'in', $order_goods_ids)->select();
    foreach ($goods_up_list as $k => $v) {
        if ($v['is_dl'] == 1) {
            $is_dl_goods = 1;
        }
    }
    if ($is_dl_goods == 1) {
        $up_info = Db::name('member')->find($member_info['invite_id']);
        //上级不存在
        if (!$up_info) {
            return null;
        }
        //上级的等级小于代理
        if ($up_info['level_id'] < 3) {
            //找最近的董事 股东 代理
            $new_invite_member = getIdentity2($up_info['id']);
            if ($new_invite_member) {
                Db::name('member')->update([
                    'id' => $member_info['id'],
                    'invite_id' => $new_invite_member['id']
                ]);
            }
        }
    }
}

function finishOrder($order_info, $type = 1)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 4,
        'finish_time' => time(),
        'finish_type' => $type
    );
    Db::name('order')->update($update_data);
//    //升级会员
//    upVip($order_info);
//    //升级首席代理
//    upDl($order_info);
//    //普通返现
//    returnMoney($order_info);
//    //级差返佣
//    jiChaMoney($order_info);
//    //9980平级将
//    PJMoney1($order_info);
//    //董事股东分红管理&&董事平级奖励
//    DSGDfxMoney($order_info);
}

//升级会员
function upVip($order_info)
{
    //判断
    $member_info = Db::name('member')->find($order_info['member_id']);
    if ($member_info['level_id'] >= 2) {
        return 0;
    }
    $order_goods_ids = Db::name('order_goods')->where([
        'order_id' => $order_info['id']
    ])->column('goods_id');
    $goods_up_list = Db::name('goods_up')->where('goods_id', 'in', $order_goods_ids)->select();
    foreach ($goods_up_list as $k => $v) {
        if ($v['is_hy'] == 1) {
            Db::name('member')->update([
                'id' => $order_info['member_id'],
                'level_id' => 2
            ]);
        }
    }
}

//升级代理
function upDl($order_info)
{
    //判断
    $member_info = Db::name('member')->find($order_info['member_id']);
    if ($member_info['level_id'] >= 3) {
        return 0;
    }
    $order_goods_ids = Db::name('order_goods')->where([
        'order_id' => $order_info['id']
    ])->column('goods_id');
    $goods_up_list = Db::name('goods_up')->where('goods_id', 'in', $order_goods_ids)->select();
    foreach ($goods_up_list as $k => $v) {
        if ($v['is_dl'] == 1) {
            Db::name('member')->update([
                'id' => $order_info['member_id'],
                'level_id' => 3
            ]);
        }
    }
}

//1直推奖励 2级差奖励 3平级奖励 4分红奖励
function returnMoney($order_info)
{
    $member = Db::name('member')->find($order_info['member_id']);
    $invite_member = Db::name('member')->where([
        'id' => $member['invite_id']
    ])->find();
    if ($invite_member) {
        $order_goods_list = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->column('goods_id');

        $goods_level_money = Db::name('goods_level_money')->where([
            ['goods_id', 'in', $order_goods_list],
            ['level_id', '=', $invite_member['level_id']]
        ])->select();

        foreach ($goods_level_money as $k => $v) {
            $order_goods = Db::name('order_goods')->where([
                'order_id' => $order_info['id'],
                'goods_id' => $v['goods_id']
            ])->find();
            $money = round($order_goods['sum_money'] * ($v['rate'] / 100), 2);
            reward($invite_member['id'], $order_info, $money, 1, $order_info['member_id'], $order_goods, $status = 1, $desc = '直推奖励', $ping_order_no = 0);
        }
    }
}

//级差奖
function jiChaMoney($order_info)
{
    //上级是980 用户
    $member_info = Db::name('member')->find($order_info['member_id']);
    $invite1m = Db::name('member')->find($member_info['invite_id']);
    if ($invite1m && $invite1m['level_id'] == 2) {
        $invite2m = Db::name('member')->find($invite1m['invite_id']);
        //上级的的上级是大于等于9980用户 返回每一项商品的10%
        if ($invite2m && $invite2m['level_id'] >= 3) {
            $order_goods_list = Db::name('order_goods')->where([
                'order_id' => $order_info['id']
            ])->select();
            foreach ($order_goods_list as $k => $v) {
                $money = round($v['sum_money'] * (0.1), 2);
                reward($invite2m['id'], $order_info, $money, 2, $order_info['member_id'], $v, $status = 1, $desc = '级差奖励', $ping_order_no = 0);
            }
        }
    }
}

//9980平级奖
function PJMoney1($order_info)
{
    //上级是980 用户
    $member_info = Db::name('member')->find($order_info['member_id']);
    $invite1m = Db::name('member')->find($member_info['invite_id']);
    if ($invite1m && $invite1m['level_id'] == 3) {
        $invite2m = Db::name('member')->find($invite1m['invite_id']);
        if ($invite2m && $invite2m['level_id'] == 3) {
            $order_goods_list = Db::name('order_goods')->where([
                'order_id' => $order_info['id']
            ])->select();
            foreach ($order_goods_list as $k => $v) {
                $money = round($v['sum_money'] * (0.02), 2);
                reward($invite2m['id'], $order_info, $money, 3, $order_info['member_id'], $v, $status = 1, $desc = '平级奖励', $ping_order_no = $order_info['order_no']);
            }
        }
    }
}


//董事股东分红管理&&董事平级奖励
function DSGDfxMoney($order_info)
{
    $member_info = Db::name('member')->find($order_info['member_id']);

    $up_user = getNearestDirector($member_info['id'],$member_info['id']);
    if ($up_user) {
        $order_goods_list = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->select();
        if ($member_info['level_id'] < 4) {
            foreach ($order_goods_list as $k => $v) {
                $money = round($v['sum_money'] * (0.1), 2);
                reward($up_user['id'], $order_info, $money, 4, $order_info['member_id'], $v, 1, '分红奖励');
            }
        }
        if ($up_user['level_id'] == 4) {
            $up_user_top = Db::name('member')->find($up_user['invite_id']);
            if ($up_user_top && $up_user_top['level_id'] == 4) {
                foreach ($order_goods_list as $k => $v) {
                    $money = round($v['sum_money'] * (0.02), 2);
                    reward($up_user_top['id'], $order_info, $money, 3, $order_info['member_id'], $v, 1, '平级奖励', $order_info['order_no']);
                }
            }
        }
    }
}

//原始股东分红管理

//获取上级最近董事或者股东
function getNearestDirector($userId, $originalUserId = null)
{
    $user = Db::name('member')
        ->where('id', $userId)
        ->find();

    if (!$user) {
        return 0;
    }

    if (($user['level_id'] == 4 || $user['level_id'] == 5) && $user['id'] != $originalUserId)  {
        return $user;
    }

    if (empty($user['invite_id'])) {
        return 0;
    }

    return getNearestDirector($user['invite_id'],$originalUserId);
}


function tui($order_id, $order_after_id = 0, $tui_money = 0)
{
    $order_info = Db::name('order')
        ->where('id', $order_id)
        ->find();
    $config = config('wechat.wxpay');
    $app = Factory::payment($config);
    if (!$tui_money) {
        $tui_money = $order_info['pay_money'];
    }
    $result = array();
    if ($order_info['pay_type'] == 1) {
        $result = $app->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['pay_money'] * 100, $tui_money * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);
    } else {
        addMoney($order_info['member_id'], 5, $tui_money, '订单退款', $order_info);
    }
    if ($order_after_id) {
        $order_after_update_data = array(
            'id' => $order_after_id,
            'status' => 5,
            'tui_money' => $tui_money,
            'finishi_time' => time()
        );
        Db::name('order_after')->update($order_after_update_data);
    }
    tuikuanServerOrder($order_info, $order_info['pay_money'], 1);
    return $result;
}

//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
//7已取消
function tuikuanServerOrder($order_info, $tui_moeny = 0.00, $is_houtui = 0)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 6,
        'is_tui' => 1,
        'pay_status' => 2,
        'tui_time' => time(),
        'is_houtui' => $is_houtui,
        'tui_moeny' => $tui_moeny
    );
    //优惠券
    if ($order_info['mc_id']) {
        Db::name('member_coupons')->update([
            'id' => $order_info['mc_id'],
            'status' => 1,
        ]);
    }
    //订单信息  order_after status 1待同意 2已同意 3已拒绝 4已发货 5已完成
    Db::name('order')->update($update_data);
    if ($is_houtui == 1) {
        $order_after = array(
            'tui_no' => 'cp' . GetOrderSN(2),
            'order_no' => $order_info['order_no'],
            'order_id' => $order_info['id'],
            'status' => 5,
            'create_time' => time(),
            'tui_reason' => '后台主动退款',
            'order_pay_money' => $order_info['pay_money'],
            'member_id' => $order_info['member_id'],
            'is_fa' => 0,
            'order_status' => 6,
            'tui_money' => $tui_moeny,
        );
        Db::name('order_after')->insertGetId($order_after);
    }
}

function getTopInviter($userId)
{
    while (true) {
        $user = Db::name('member')->where(['id' => $userId])->find();
        if (!$user) {
            return null; // 用户不存在
        }
        // 如果当前用户的 invite_id 为 0，说明是顶级用户
        if ($user['invite_id'] == 0) {
            return $user;
        }
        // 继续查找邀请人
        $userId = $user['invite_id'];
    }
}

//获取最近上级有身份的人
function getIdentity($userId)
{
    while (true) {
        $user = Db::name('member')->where(['id' => $userId])->find();
        if (!$user) {
            return null; // 用户不存在
        }
        if ($user['level_id'] > 1) {
            return $user;
        }
        // 如果当前用户的 invite_id 为 0，说明是顶级用户
        if ($user['invite_id'] == 0) {
            return null;
        }
        // 继续查找邀请人
        $userId = $user['invite_id'];
    }
}

//获取最近上级大于等于代理的人
function getIdentity2($userId)
{
    while (true) {
        $user = Db::name('member')->where(['id' => $userId])->find();
        if (!$user) {
            return null; // 用户不存在
        }
        if ($user['level_id'] > 2) {
            return $user;
        }
        // 如果当前用户的 invite_id 为 0，说明是顶级用户
        if ($user['invite_id'] == 0) {
            return null;
        }
        // 继续查找邀请人
        $userId = $user['invite_id'];
    }
}

//获取邀请
function getInvite($invite_id)
{
    //上级id 老板id 顶级id
    //invite_id boss_invite_id top_invite_id
    $return_data = array(
        'invite_id' => 0,
        'boss_invite_id' => -1,//老板不确定
        'top_invite_id' => 0
    );
    $member_info = Db::name('member')->where(['id' => $invite_id])->find();
    if (!$member_info) {
        return $return_data;
    }
//    if ($member_info['level_id'] <= 1) {
//        return $return_data;
//    }
    $top_user = getTopInviter($invite_id);
    $invite_user = getIdentity($invite_id);
    if ($top_user) {
        $return_data['top_invite_id'] = $top_user['id'];
    }
    if ($invite_user) {
        $return_data['invite_id'] = $invite_user['id'];
    }
    if ($member_info['level_id'] > 2) {
        $return_data['boss_invite_id'] = $invite_id;
    }
    return $return_data;
}


//type 类型 1后台充值 2转账支出 3转账收入 4购买消费 5订单退款 8提现  9直推奖励 10级差奖励 11平级奖励 12分红奖励 16团队奖
function addMoney($member_id, $type, $money, $desc, $order_info = null, $get_member_id = 0, $send_member_id = 0)
{

    $insert_data = array(
        'member_id' => $member_id,
        'money' => $money,
        'get_member_id' => $get_member_id,
        'send_member_id' => $send_member_id,
        'type' => $type,
        'desc' => $desc,
        'create_time' => time()
    );
    if ($order_info) {
        $insert_data['order_id'] = $order_info['id'];
        $insert_data['order_no'] = $order_info['order_no'];
    }
    if ($money > 0) {
        $insert_data['is_count'] = 1;
    } else {
        $insert_data['is_count'] = 2;
    }
    Db::name('member')->where(['id' => $member_id])->setInc('money', $money);
    $insert_id = Db::name('member_finance')->insertGetId($insert_data);
    return $insert_id;
}

// member_finance 1后台充值 2转账支出 3转账收入 4购买消费 5订单退款 8提现  9直推奖励 10级差奖励 11平级奖励 12分红奖励 16团队奖
// reward                                                           1直推奖励 2级差奖励 3平级奖励 4分红奖励 6团队奖
function reward($member_id, $order_info, $money, $type, $junior_member_id, $order_goods, $status = 0, $desc = '奖励', $ping_order_no = 0)
{
    if ($money == 0) {
        return;
    }
    $insert_data = array(
        'member_id' => $member_id,
        'money' => $money,
        'type' => $type,
//        'order_id' => $order_info['id'],
//        'order_no' => $order_info['order_no'],
        'junior_member_id' => $junior_member_id,
        'status' => $status,
//        'goods_id' => $order_goods['goods_id'],
//        'goods_num' => $order_goods['num'],
        'ping_order_no' => $ping_order_no,
        'create_time' => time(),
        'desc' => $desc
    );

    if (!$order_info) {
        $insert_data['order_id'] = 0;
        $insert_data['order_no'] = 0;
    } else {
        $insert_data['order_id'] = $order_info['id'];
        $insert_data['order_no'] = $order_info['order_no'];
    }
    if (!$order_goods) {
        $insert_data['goods_id'] = 0;
        $insert_data['goods_num'] = 0;
    } else {
        $insert_data['goods_id'] = $order_goods['goods_id'];
        $insert_data['goods_num'] = $order_goods['num'];
    }

    $insert_id = Db::name('reward')->insertGetId($insert_data);
    if ($status) {
        $member_finance_type = 0;
        switch ($type) {
            case 1:
                $member_finance_type = 9;
                break;
            case 2:
                $member_finance_type = 10;
                break;
            case 3:
                $member_finance_type = 11;
                break;
            case 4:
                $member_finance_type = 12;
                break;
            case 6:
                $member_finance_type = 16;
                break;
        }
        addMoney($member_id, $member_finance_type, $money, $desc, $order_info);
    }
    return $insert_id;
}


//输入id获取团队id 不包括本id
function getTeamMembersRecursive($userId)
{
    $teamMembers = [];
    // 查询当前用户直接邀请的用户
    $directMembers = Db::name('member')
        ->where('invite_id', $userId)
        ->column('id');

    // 将直接邀请的用户加入团队
    $teamMembers = array_merge($teamMembers, $directMembers);

    // 递归获取间接邀请的用户
    foreach ($directMembers as $memberId) {
        $teamMembers = array_merge($teamMembers, getTeamMembersRecursive($memberId));
    }
    return $teamMembers;
}

//输入id获取团队id 不包括本id 根据用户加入时间
function getTeamMembersRecursive_time($userId, $year, $month)
{
    $timeScope = getTimeScope($year . '-' . $month);
    $teamMembers = [];
    // 查询当前用户直接邀请的用户
    $directMembers = Db::name('member')
        ->where('invite_id', $userId)
        ->where('create_time', '<=', $timeScope['endTimestamp'])
        ->column('id');

    // 将直接邀请的用户加入团队
    $teamMembers = array_merge($teamMembers, $directMembers);

    // 递归获取间接邀请的用户
    foreach ($directMembers as $memberId) {
        $teamMembers = array_merge($teamMembers, getTeamMembersRecursive($memberId));
    }
    return $teamMembers;
}

//团队返回金额
function calculateTeamReward($amount)
{
    // 定义奖励规则
    $rewardRules = [
        20000 => 0.01,
        100000 => 0.02,
        500000 => 0.03,
        1000000 => 0.05,
        2000000 => 0.07,
    ];
    // 如果业绩少于1万，返回0
    if ($amount < 10000) {
        return 0;
    }
    // 遍历奖励规则，找到对应的百分比
    $rewardPercentage = 0;
    foreach ($rewardRules as $threshold => $percentage) {
        if ($amount >= $threshold) {
            $rewardPercentage = $percentage;
        } else {
            break;
        }
    }

    // 计算奖励金额
    $rewardAmount = round($amount * $rewardPercentage, 2);
    return $rewardAmount;
}

//输入年月获取时间戳的范围
function getTimeScope($time)
{
    $startTimestamp = strtotime($time . '-01 00:00:00');
// 获取该月的最后一天的时间戳
    $endTimestamp = strtotime(date('Y-m-t 23:59:59', $startTimestamp));
    $data['startTimestamp'] = $startTimestamp;
    $data['endTimestamp'] = $endTimestamp;
    return $data;
}

function getEffectOrderMoney($member_ids, $startTimestamp, $endTimestamp)
{
    $money = Db::name('order')->where([
        ['member_id', 'in', $member_ids],
        ['status', 'in', [2, 3, 4, 5]],
        ['create_time', 'between', [$startTimestamp, $endTimestamp]],
//        ['finish_time', 'between', [$startTimestamp, $endTimestamp]],
    ])->sum('order_money');
//    if ($effect_order_ids) {
//        $money = Db::name('order_goods')->where([
//            ['order_id', 'in', $effect_order_ids],
//        ])->sum('sum_money');
//    }
    return $money;
}
function getcYeJi2($member_ids, $startTimestamp, $endTimestamp)
{
    $money= Db::name('member_yeji')->where([
        ['member_id','in',$member_ids],
        ['create_time', 'between', [ $startTimestamp, $endTimestamp]],
    ])->sum('money');
    return $money;
}

//获取团队业绩按照年月查询
function teamMoney($year, $month, $member_id)
{
    $timeScope = getTimeScope($year . '-' . $month);
    //获取我的直属下级
    $junior_ids = Db::name('member')->where([
        'invite_id' => $member_id,
    ])->column('id');
    //本人的订单金额
    $money = getEffectOrderMoney($member_id, $timeScope['startTimestamp'], $timeScope['endTimestamp']);
    //遍历每个下级 获取下级的团队id 包含这个下级id
    //键值为下级id 团队金额 团队奖励
    $junior_team = array();
    foreach ($junior_ids as $k => $v) {
        $teamMembers = getTeamMembersRecursive($v);
        array_unshift($teamMembers, $v);//在团队中加入自己
        $team_money = getEffectOrderMoney($teamMembers, $timeScope['startTimestamp'], $timeScope['endTimestamp']);
        //获取$memberId 团队的所有订单金额
        $money += $team_money;
        $junior_team[$v]['member_id'] = $v;
        $junior_team[$v]['team_ids'] = $teamMembers;
        $junior_team[$v]['order_money'] = $team_money;
        $junior_team[$v]['reward'] = calculateTeamReward($team_money);
    }
    $my_reward = calculateTeamReward($money);
    foreach ($junior_team as $k => $v) {
        $member_info = Db::name('member')->find($k);
        //todo 用户必须是首席代理才行
        if ($member_info['level_id'] >= 3) {
            $my_reward -= $v['reward'];
        }
    }
    $return_date['junior_team'] = $junior_team;
    $return_date['money'] = $my_reward;
    $return_date['performance'] = $money;
    $return_date['team_num'] = count(getTeamMembersRecursive($member_id));
    return $return_date;
}
//线下总业绩
function cZongYeJi($member_id){
    $team_ids = getTeamMembersRecursive($member_id);
    array_unshift($team_ids, $member_id);
    $cyeji=Db::name('member')->where('id','in',$team_ids)->sum('cyeji');
    return $cyeji;
}

function getEffectOrderMoneySum($member_ids)
{
    $money = Db::name('order')->where([
        ['member_id', 'in', $member_ids],
        ['status', 'in', [2, 3, 4, 5]],
    ])->sum('order_money');
    return $money;
}

function teamMoneySum($member_id)
{
    $teamMembers = getTeamMembersRecursive($member_id);
    array_unshift($teamMembers, $member_id);//在团队中加入自己
    $money = getEffectOrderMoneySum($teamMembers);
    return $money;
}


//间隔天数
function getDaysDiff($send_time, $current_time = null)
{
    $current_time = $current_time ?? time();
    return abs(floor(($current_time - $send_time) / 86400));
}

//增加团队奖励
function sendTeamMoney($lastMonthYear, $member_id, $money, $performance, $team_num)
{
    $insert_data = array(
        'time' => $lastMonthYear,
        'member_id' => $member_id,
        'money' => $money,
        'performance' => $performance,
        'team_num' => $team_num,
        'create_time' => time()
    );
    $id = Db::name('team_money')->insertGetId($insert_data);
    //todo 增加团队奖励
    addMoney($member_id, 16, $money, '团队奖励');
    return $id;
}

//获取商品优惠金额 通过个人身份
function getDiscountMoney($member_info, $goods_id, $goods_price)
{
    $cate_level_discount = Db::name('cate_level_discount')
        ->where([
            'goods_id' => $goods_id,
            'level_id' => $member_info['level_id']
        ])->find();
    $money = 0;
    if ($cate_level_discount) {
        $money = round((100 - $cate_level_discount['discount']) / 100 * $goods_price, 2);
    }
    return $money;
}

//==================================================================123=================================================
/**
 * 微信发货
 */
function WxSendOrderGoods($post, $token)
{


    $currentTime = new DateTime();

// 设置时区
    $currentTime->setTimezone(new DateTimeZone('UTC'));

// 将当前时间格式化为 RFC 3339 格式
    $rfc3339Time = $currentTime->format(DateTime::RFC3339);

    $use = SelectModelData('order', ['ordersn' => $post['ordersn']], 1);
    $user_token = $use['token'];
    $openid = SelectModelData('member', ['token' => $user_token], 1, 'openid');

    $config = [
        'app_id' => config('appid'),
        'mch_id' => config('mch_id'),
        'key' => config('paySecret'),
        'cert_path' => '', // XXX: 绝对路径！！！！
        'key_path' => '',      // XXX: 绝对路径！！！！
        'notify_url' => conf("lm", "url") . 'payres',
    ];

    $app = Factory::payment($config);

    $result = $app->order->queryByOutTradeNumber($post['ordersn']);

//    dump($result['transaction_id']);die;

    $str = "商品订单";

    $str_utf8 = mb_convert_encoding($str, "UTF-8", "auto");


    $sjrxx = GetAddress($use['address_id']);
    $iszt = intval($post['iszt']);
    if ($iszt == 1) {
        $arr = [
            'ordersn' => $post['ordersn'],
            'type' => 4,
//                'tracking_no'       =>$data['emsid'],
//                'express_company'   =>$data['delivery_id'],
            'cptitle' => '购买产品',
            'jjrtel' => config('tel'),
            'sjrtel' => $sjrxx['tel'],
            'openid' => $openid,
        ];
    } else {
        $arr = [
            'ordersn' => $post['ordersn'],
            'type' => 1,
            'tracking_no' => $post['emsid'],
            'express_company' => $post['delivery_id'],
            'cptitle' => '购买产品',
            'jjrtel' => maskPhone(config('tel')),
            'sjrtel' => maskPhone($sjrxx['tel']),
            'openid' => $openid,
        ];
    }


    $data = [
        'order_key' => [
            'order_number_type' => 1,
//                'transaction_id' => $result['transaction_id'],
            'mchid' => $result['mch_id'],
            'out_trade_no' => $arr['ordersn'] . 'ab'
        ],
        'logistics_type' => intval($arr['type']), //1/物流，4/自提
        'delivery_mode' => 1,
        'shipping_list' => [[
            'tracking_no' => $arr['tracking_no'],
            'express_company' => $post['delivery_id'],
            'item_desc' => $arr['cptitle'],
            'contact' => [
                'consignor_contact' => $arr['jjrtel'],
                'receiver_contact' => $arr['sjrtel']
            ],
        ]],
        'upload_time' => $rfc3339Time,
        'payer' => [
            'openid' => $arr['openid']
        ]
    ];

    $postUrl = sprintf("https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=%s", $token);

    // 将数组转化为JSON格式
    $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
    // 发起POST请求
    $result = string2array(curlPost($postUrl, $jsonData));

    return $result;


}


/**
 * 将字符串转换为数组
 *
 * @param string $data 字符串
 * @return   array   返回数组格式，如果，data为空，则返回空数组
 */
function string2array($data)
{
//    $data = trim($data);
    if ($data == '') return array();
    if (strpos($data, 'array') === 0) {
        @eval("\$array = $data;");
    } else {
        if (strpos($data, '{\\') === 0) $data = stripslashes($data);
        $array = json_decode(htmlspecialchars_decode($data), true);
    }
    return $array;
}


function curlPost($url = '', $postData = '', $options = array())
{
    if (is_array($postData)) {
        $postData = http_build_query($postData);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
    if (!empty($options)) {
        curl_setopt_array($ch, $options);
    }
    //https请求 不验证证书和host
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}


/**
 * 微信确认收货
 */
function WxSendqrshOrder($post, $token)
{
    $config = [
        'app_id' => config('appid'),
        'mch_id' => config('mch_id'),
        'key' => config('paySecret'),
        'cert_path' => '', // XXX: 绝对路径！！！！
        'key_path' => '',      // XXX: 绝对路径！！！！
        'notify_url' => conf("lm", "url") . 'payres',
    ];

    $app = Factory::payment($config);

    $result = $app->order->queryByOutTradeNumber($post['ordersn']);

//    dump($result['transaction_id']);die;

    $str = "购买产品";

    $str_utf8 = mb_convert_encoding($str, "UTF-8", "auto");


    $data = [
        'transaction_id' => $result['transaction_id'],
        'merchant_id' => $result['mch_id'],
        'received_time' => time()
    ];
    $postUrl = sprintf("https://api.weixin.qq.com/wxa/sec/order/notify_confirm_receive?access_token=%s", $token);

    // 将数组转化为JSON格式
    $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
    // 发起POST请求
    $result = string2array(curlPost($postUrl, $jsonData));
    return $result;
}

//输入用户id获取用户的服务中心 分公司 董事
function getUpperLevelIds($user_id)
{
    $result = [
        'service_center_id' => 0,
        'branch_id' => 0,
        'director_id' => 0,
    ];

    // 先获取当前用户的 invite_id，直接从上一层开始找
    $current_user = Db::name('user')
        ->where('id', $user_id)
        ->field('invite_id')
        ->find();

    if (!$current_user || $current_user['invite_id'] == 0) {
        return $result; // 没有邀请人，直接返回空
    }

    $current_id = $current_user['invite_id']; // 从邀请人开始找

    // 最多查询100层，防止死循环
    $max_level = 100;
    $current_level = 0;

    while ($current_id != 0 && $current_level < $max_level) {
        $current_level++;

        // 查询当前用户的信息
        $user = Db::name('user')
            ->where('id', $current_id)
            ->field('id, invite_id, level_id')
            ->find();

        if (!$user) {
            break; // 用户不存在，终止
        }

        // 检查 level_id 并记录
        switch ($user['level_id']) {
            case 4: // 服务中心
                if (is_null($result['service_center_id'])) {
                    $result['service_center_id'] = $user['id'];
                }
                break;
            case 5: // 分公司
                if (is_null($result['branch_id'])) {
                    $result['branch_id'] = $user['id'];
                }
                break;
            case 6: // 董事
                if (is_null($result['director_id'])) {
                    $result['director_id'] = $user['id'];
                }
                break;
        }

        // 如果已经找到所有目标，提前终止
        if (
            !is_null($result['service_center_id']) &&
            !is_null($result['branch_id']) &&
            !is_null($result['director_id'])
        ) {
            break;
        }

        // 继续向上查找
        $current_id = $user['invite_id'];
    }

    return $result;
}

//显示每个角色的层级关系 测试
function getUpperLevelIds2($user_id)
{
    $result = [
        'hierarchy' => [],            // 记录查找顺序
        'service_center_id' => null,   // 服务中心ID
        'branch_id' => null,          // 分公司ID
        'director_id' => null,        // 董事ID
    ];

    // 先获取当前用户的 invite_id，直接从上一层开始找（不包含自己）
    $current_user = Db::name('member')
        ->where('id', $user_id)
        ->field('invite_id')
        ->find();

    if (!$current_user || $current_user['invite_id'] == 0) {
        return $result; // 没有邀请人，直接返回空
    }

    $current_id = $current_user['invite_id']; // 从邀请人开始找
    $current_level = 1; // 层级计数（从1开始）

    // 最多查询100层，防止死循环
    $max_level = 100;

    while ($current_id != 0 && $current_level <= $max_level) {
        // 查询当前用户的信息
        $user = Db::name('member')
            ->where('id', $current_id)
            ->field('id, invite_id, level_id')
            ->find();


        if (!$user) {
            break; // 用户不存在，终止
        }

        // 记录当前层级信息
        $result['hierarchy'][] = [
            'level' => $current_level,
            'user_id' => $user['id'],
            'user_level' => $user['level_id'],
        ];

        // 检查 level_id 并记录
        switch ($user['level_id']) {
            case 4: // 服务中心
                if (is_null($result['service_center_id'])) {
                    $result['service_center_id'] = $user['id'];
                }
                break;
            case 5: // 分公司
                if (is_null($result['branch_id'])) {
                    $result['branch_id'] = $user['id'];
                }
                break;
            case 6: // 董事
                if (is_null($result['director_id'])) {
                    $result['director_id'] = $user['id'];
                }
                break;
        }

        // 如果已经找到所有目标，提前终止
        if (
            !is_null($result['service_center_id']) &&
            !is_null($result['branch_id']) &&
            !is_null($result['director_id'])
        ) {
            break;
        }

        // 继续向上查找
        $current_id = $user['invite_id'];
        $current_level++;
    }

    return $result;
}

function getUpperLevelIds3($user_id)
{
    $result = [
        'member' => null,
        'service_center' => null,   // 服务中心ID
        'branch' => null,          // 分公司ID
        'director' => null,        // 董事ID
    ];

    // 先获取当前用户的 invite_id，直接从上一层开始找（不包含自己）
    $current_user = Db::name('member')
        ->where('id', $user_id)
        ->field('invite_id,id,level_id')
        ->find();
    $result['member']['member_id'] = $current_user['id'];
    $result['member']['level_id'] = $current_user['level_id'];

    if (!$current_user || $current_user['invite_id'] == 0) {
        return $result; // 没有邀请人，直接返回空
    }

    $current_id = $current_user['invite_id']; // 从邀请人开始找
    $current_level = 1; // 层级计数（从1开始）

    // 最多查询100层，防止死循环
    $max_level = 100000;

    while ($current_id != 0 && $current_level <= $max_level) {
        // 查询当前用户的信息
        $user = Db::name('member')
            ->where('id', $current_id)
            ->field('id, invite_id, level_id')
            ->find();

        if (!$user) {
            break; // 用户不存在，终止
        }

        // 检查 level_id 并记录
        switch ($user['level_id']) {
            case 4: // 服务中心
                if (is_null($result['service_center'])) {
                    $result['service_center']['member_id'] = $user['id'];
                    $result['service_center']['level_id'] = $user['level_id'];
                    $result['service_center']['top'] = $current_level;
                }
                break;
            case 5: // 分公司
                if (is_null($result['branch'])) {
                    $result['branch']['member_id'] = $user['id'];
                    $result['branch']['level_id'] = $user['level_id'];
                    $result['branch']['top'] = $current_level;
                }
                break;
            case 6: // 董事
                if (is_null($result['director'])) {
                    $result['director']['member_id'] = $user['id'];
                    $result['director']['level_id'] = $user['level_id'];
                    $result['director']['top'] = $current_level;
                }
                break;
        }

        // 如果已经找到所有目标，提前终止
        if (
            !is_null($result['service_center']) &&
            !is_null($result['branch']) &&
            !is_null($result['director'])
        ) {
            break;
        }

        // 继续向上查找
        $current_id = $user['invite_id'];
        $current_level++;
    }

    return $result;
}

//输入时间戳 获取每年每月
function generateYearMonthArray($timestamp, $endTimestamp = null)
{
    $start = new DateTime("@$timestamp");
    $start->setTime(0, 0, 0); // 时间归零，避免时区影响
    $start->modify('first day of this month'); // 从当月1日开始

    $end = $endTimestamp ? new DateTime("@$endTimestamp") : new DateTime();
    $end->modify('first day of this month'); // 结束时间也取当月1日

    $interval = new DateInterval('P1M'); // 按月递增
    $period = new DatePeriod($start, $interval, $end);

    $result = [];
    foreach ($period as $date) {
        $result[] = $date->format('Y-m');
    }

    return $result;
}

//todo 首席代理 及以上才有全员分红
// 董事 股东购买不给上级管理分红










